/* Copyright 2011 Rok Lenarčič 
 * 
 * This file is a part of MicroFn.
 * 
 * MicroFn is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * MicroFn is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.

 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/> */

package net.rlenar.microfn;

import java.util.Iterator;
import java.util.NoSuchElementException;
/**
 * 
 * @author rok.lenarcic
 * Iterator that's iterable at the same time.
 * to be reusable.
 * 
 * @param <T>
 */
public abstract class SingleCheckIterator<T> implements Iterable<T>, Iterator<T> {

	private boolean alreadyChecked = false;
	private boolean hasNext = false;
	public abstract SingleCheckIterator<T> iterator();
	public void remove() {
		throw new UnsupportedOperationException();
	}	
	public boolean hasNext() {
		if (alreadyChecked) {
			return hasNext;
		} else {
			alreadyChecked = true;
			hasNext = existsNext();
			return hasNext;
		}
	}
	/**
	 * Guaranteed to be called exactly once per element.
	 * @return if there exists another element
	 */
	protected abstract boolean existsNext();
	/**
	 * Guaranteed to be called exactly once per element.
	 * Guaranteed that existsNext is called once before this function is called
	 * Guaranteed that this method will not be called if existsNext returns false;
	 * Should not call hasNext or next on this object!
	 * @return next element
	 */
	protected abstract T generateNext();
	public T next() {
		if (hasNext()) {
			T ret = generateNext();
			alreadyChecked = false;
			return ret;
		} else {
			throw new NoSuchElementException();
		}
	}
	@Override
	public String toString() {
		return PrettyPrint.prettyPrint(this);
	}

}
